<template>
  <view class="add-form-container">
      <!-- 使用封装的页面头部组件 -->
      <page-header
          :title="isEdit ? '编辑灾害天气' : '灾害天气'"
      ></page-header>

      <!-- 使用灾害类型选择器组件 -->
      <DisasterTypeSelector
          v-model="formData.disasterType"
      ></DisasterTypeSelector>

      <!-- 使用地块选择器组件 -->
      <LandSelector
          ref="landSelector"
          @selection-change="handleLandSelectionChange"
      ></LandSelector>

      <!-- 使用条田选择器组件 -->
      <SectionSelector
          ref="sectionSelector"
          @areaChange="handleAreaChange"
          @usersChange="handleUsersChange"></SectionSelector>

      <view class="basic-info">
          <view class="section-title">基础信息</view>

          <uni-forms
              ref="form"
              :modelValue="formData"
              :rules="rules"
              validateTrigger="bind"
              label-position="top"
              label-width="200"
              class="farm-form"
          >
              <uni-forms-item label="灾害发生日期" name="dateRange" required>
                  <uni-datetime-picker
                      type="daterange"
                      v-model="formData.dateRange"
                      :border="false"
                      :label-width="200"
                      @change="dateRangeChange"
                  >
                      <view class="uni-date-picker-container">
                          <text
                              :class="{
                                  placeholder: !formData.dateRangeText,
                              }"
                              >{{
                                  formData.dateRangeText || "请选择灾害发生日期"
                              }}</text
                          >
                          <view class="date-icon">
                              <roc-icon-plus
                                  type="fas"
                                  name="calendar-alt"
                                  :size="18"
                                  color="#999"
                              ></roc-icon-plus>
                          </view>
                      </view>
                  </uni-datetime-picker>
              </uni-forms-item>
              
              <!-- 新增：灾害等级/程度 -->
              <uni-forms-item label="灾害等级/程度" name="disasterLevel" required>
                  <view class="severity-options">
                      <view 
                          class="severity-item" 
                          :class="{ active: formData.disasterLevel === '2' }"
                          @click="formData.disasterLevel = '2'"
                      >
                          <view class="severity-indicator mild"></view>
                          轻度
                      </view>
                      <view 
                          class="severity-item" 
                          :class="{ active: formData.disasterLevel === '1' }"
                          @click="formData.disasterLevel = '1'"
                      >
                          <view class="severity-indicator medium"></view>
                          中度
                      </view>
                      <view 
                          class="severity-item" 
                          :class="{ active: formData.disasterLevel === '0' }"
                          @click="formData.disasterLevel = '0'"
                      >
                          <view class="severity-indicator severe"></view>
                          重度
                      </view>
                  </view>
              </uni-forms-item>

              <uni-forms-item label="土地面积" name="area" required>
                  <uni-easyinput
                      type="digit"
                      v-model="formData.area"
                      placeholder="请输入"
                      disabled
                  >
                      <template #right>
                          <text class="input-unit">亩</text>
                      </template></uni-easyinput
                  >
              </uni-forms-item>
              <uni-forms-item label="影响描述" name="impactDescription">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.impactDescription"
                        placeholder="请输入"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>

              <uni-forms-item label="负责人" name="personInCharge" required>
                  <uni-easyinput
                      v-model="formData.personInCharge"
                      placeholder="请输入负责人姓名"
                      disabled></uni-easyinput>
              </uni-forms-item>
              <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="请输入"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>

          </uni-forms>
      </view>

      <view class="photo-section">
          <view class="section-title">现场照片</view>

          <image-uploader
              ref="imageUploader"
              :images="formData.images"
              :maxCount="9"
          />
      </view>
      <view class="submit-btn-container">
          <view class="submit-btn" @click="submitForm">点击上传</view>
      </view>
  </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";
import LandSelector from "@/components/LandSelector/index.vue";
import SectionSelector from "@/components/SectionSelector/index.vue";
import ImageUploader from "@/components/ImageUploader/index.vue";
import DisasterTypeSelector from "@/components/DisasterTypeSelector/index.vue";
import { seed } from "@/utils/api/index.js";
import { weatherDisaster } from "@/utils/api/index.js";
import { formatDate, getDefaultDateRange } from "@/utils/util.js";
import { mapGetters, mapActions } from "vuex";

export default {
  components: {
      PageHeader,
      LandSelector,
      SectionSelector,
      ImageUploader,
      DisasterTypeSelector,
  },
  computed: {
      ...mapGetters({
          getDictByType: "getDictByType",
          getDictLabel: "getDictLabel",
          userInfo: "getUserInfo"
      }),
  },
  data() {
      const defaultDateRange = getDefaultDateRange()
      return {
          isEdit: false,
          editId: null,
          formData: {
              cropType: "",
              seedName: "",
              area: "",
              dateRange: defaultDateRange.dateRange,
              dateRangeText: defaultDateRange.dateRangeText,
              personInCharge: "",
              personInId: "",
              sowingMethod: "",
              machineryName: "",
              images: [],
              plotId: "", // 地块ID
              fieldId: "", // 条田ID
              remark: "", // 备注
              disasterLevel: "", // 新增
              disasterType: "",  // 灾害类型（新增）
              impactDescription: "",  
          },
          rules: {
              dateRange: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请选择灾害发生日期",
                      },
                  ],
              },
              cropType: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请选择农作物类型",
                      },
                  ],
              },
              seedName: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请选择种子名称",
                      },
                  ],
              },
              area: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请输入土地面积",
                      },
                      {
                          format: "number",
                          errorMessage: "请输入有效的数字",
                      },
                  ],
              },
              personInCharge: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请输入负责人",
                      },
                  ],
              },
              sowingMethod: {
                  rules: [
                      {
                          required: true,
                          errorMessage: "请选择播种方式",
                      },
                  ],
              },
              disasterLevel: {
                  rules: [
                      { required: true, errorMessage: "请选择灾害等级/程度" },
                  ],
              },
              disasterType: {
                  rules: [
                      { required: true, errorMessage: "请选择灾害类型" },
                  ],
              },
          },
          selectedLands: [],
          selectedSections: [],
          cropTypesData: [], // 农作物类型数据
          currentSeedNamesData: [], // 当前选中农作物类型的种子名称数据
          seedMethodsData: [], // 播种方式数据
          seedMachinesData: [], // 播种机械数据
      };
  },
  onLoad(options) {
       // 加载字典数据
       this.loadDictData();
      if (options.id) {
          this.isEdit = true;
          this.editId = parseInt(options.id);
          this.loadSeedData(this.editId);
      } else {
          // 设置默认的负责人和负责人ID
          console.log('用户信息', this.userInfo)
          this.formData.personInId = this.userInfo.id
          this.formData.personInCharge = this.userInfo.nickname
      }
  },
  methods: {
      ...mapActions(["getDictByType"]),

      // 加载字典数据
      async loadDictData() {
          console.log("加载字典数据11");
          try {
              uni.showLoading({ title: "加载字典数据..." });

              // 加载农作物类型字典
              await this.getDictByType("crop_name_type");
              this.cropTypesData =
                  this.formatDictToSelectData("crop_name_type");

              // 加载播种方式字典
              await this.getDictByType("seeding_method");
              this.seedMethodsData =
                  this.formatDictToSelectData("seeding_method");

              // 加载播种机械字典
              await this.getDictByType("sowing_machinery");
              this.seedMachinesData =
                  this.formatDictToSelectData("sowing_machinery");

              uni.hideLoading();
          } catch (error) {
              console.error("加载字典数据失败:", error);
              uni.hideLoading();
              uni.showToast({
                  title: "加载字典数据失败",
                  icon: "none",
              });
          }
      },

      // 将字典数据格式化为下拉选择框所需的格式
      formatDictToSelectData(dictType) {
          const dictList = this.getDictByType(dictType);
          return dictList.map((item) => ({
              value: item.value,
              text: item.label,
          }));
      },

      async loadSeedData(id) {
          try {
              uni.showLoading({ title: "加载中..." });

              // 调用API获取播种记录详情
              const res = await weatherDisaster.getDisasterWeather(id);

              if (res.code === 0 && res.data) {
                  const seedData = res.data;

                  // 设置日期范围
                  let startDate, endDate;
                  if (seedData.startDate) {
                      startDate = new Date(seedData.startDate);
                      endDate = seedData.endDate
                          ? new Date(seedData.endDate)
                          : new Date(seedData.startDate);
                  } else {
                      startDate = new Date(seedData.createTime);
                      endDate = new Date(seedData.createTime);
                      endDate.setDate(endDate.getDate() + 1);
                  }

                  this.formData = {
                      cropType: seedData.cropType || seedData.cropName || "",
                      seedName: seedData.seedName || "",
                      area: seedData.area ? seedData.area.toString() : "",
                      dateRange: [
                          startDate.toISOString().split("T")[0],
                          endDate.toISOString().split("T")[0],
                      ],
                      dateRangeText: `${formatDate(
                          startDate
                      )} 至 ${formatDate(endDate)}`,
                      personInCharge: seedData.personInCharge || "",
                      sowingMethod: seedData.sowingMethod || "",
                      machineryName: seedData.machineryName || "",
                      images: this.formatImages(seedData.images),
                      plotId: seedData.plotId || "",
                      fieldId: seedData.fieldId || "",
                      remark: seedData.remark || "",
                      disasterLevel: seedData.disasterLevel || "",
                      disasterType: seedData.disasterType || "",
                      impactDescription: seedData.impactDescription || "",
                  };

                  // 初始化种子名称下拉数据
                  this.handleSeedTypeChange();

                  // 等待组件加载完成后，设置地块选择状态
                  this.$nextTick(() => {
                      // 确保组件已完全加载
                      setTimeout(() => {
                          // 设置地块选择器中选中的地块
                          if (
                              this.$refs.landSelector &&
                              this.formData.plotId
                          ) {
                              this.$refs.landSelector.setSelectedLands(
                                  this.formData.plotId
                              );
                              this.updateSelectedLands();

                              // 更新条田选择器的地块ID
                              if (this.$refs.sectionSelector) {
                                  this.$refs.sectionSelector.setSelectedParcels(
                                      this.selectedLands
                                  );

                                  // 设置条田选择状态
                                  if (this.formData.fieldId) {
                                      this.$refs.sectionSelector.setSelectedFields(
                                          this.formData.fieldId
                                      );
                                      this.updateSelectedSections();
                                  }
                              }
                          }
                      }, 1200);
                  });
              } else {
                  uni.showToast({
                      title: "获取数据失败",
                      icon: "none",
                  });
              }
              uni.hideLoading();
          } catch (error) {
              console.error("加载数据失败:", error);
              uni.hideLoading();
              uni.showToast({
                  title: "加载数据失败",
                  icon: "none",
              });
          }
      },

      // 格式化图片字段，将字符串转为数组
      formatImages(images) {
          if (!images) return [];
          if (typeof images === "string") {
              if (images.includes(",")) {
                  return images.split(",");
              }
              return [images];
          }
          return Array.isArray(images) ? images : [];
      },

      dateRangeChange(e) {
          if (e && e.length === 2) {
              const startDate = new Date(e[0]);
              const endDate = new Date(e[1]);
              this.formData.dateRangeText = `${formatDate(
                  startDate
              )} 至 ${formatDate(endDate)}`;
          } else {
              this.formData.dateRangeText = "";
          }
      },

      async handleSeedTypeChange() {
          // 根据选择的农作物类型，更新种子名称下拉选项
          if (this.formData.cropType) {
              try {
                  // 根据选中的农作物类型获取对应的种子名称字典
                  const cropTypeValue = this.formData.cropType;

                  // 从字典中获取对应的种子类型值
                  const cropTypeDict = this.getDictByType("crop_name_type");
                  const selectedCrop = cropTypeDict.find(
                      (item) => item.value === cropTypeValue
                  );

                  if (selectedCrop) {
                      // 加载对应的种子名称字典
                      await this.getDictByType(selectedCrop.value);
                      this.currentSeedNamesData = this.formatDictToSelectData(
                          selectedCrop.value
                      );
                  } else {
                      this.currentSeedNamesData = [];
                  }
              } catch (error) {
                  console.error("获取种子名称字典失败:", error);
                  this.currentSeedNamesData = [];
              }
          } else {
              this.currentSeedNamesData = [];
          }

          // 重置种子名称
          if (
              this.formData.seedName &&
              !this.currentSeedNamesData.some(
                  (item) => item.value === this.formData.seedName
              )
          ) {
              this.formData.seedName = "";
          }
      },
      handleLandSelectionChange() {
          this.updateSelectedLands();
      },
      handleAreaChange(area) {
          this.formData.area = area;
      },

      handleUsersChange(users) {
          this.formData.personInId = users.map((item) => item.userId).join(',');
          this.formData.personInCharge = users.map((item) => item.userName).join(',');
      },

      // 更新选中的地块数据
      updateSelectedLands() {
          if (this.$refs.landSelector) {
              this.selectedLands = this.$refs.landSelector.getSelectedLands();
              console.log("更新选中的地块:", this.selectedLands);

              // 当地块选择变化时，更新条田选择器
              if (this.$refs.sectionSelector) {
                  this.$refs.sectionSelector.setSelectedParcels(
                      this.selectedLands
                  );
                  // 更新选中的条田
                  this.updateSelectedSections();
              }
          }
      },

      // 更新选中的条田数据
      updateSelectedSections() {
          if (this.$refs.sectionSelector) {
              this.selectedSections =
                  this.$refs.sectionSelector.getSelectedSections();
              console.log("更新选中的条田:", this.selectedSections);
          }
      },

      validateForm() {
          // 更新选中的地块和条田
          this.updateSelectedLands();
          this.updateSelectedSections();

          // 检查是否选择了地块
          if (!this.$refs.landSelector.validate()) {
              uni.showToast({
                  title: "请选择至少一个地块",
                  icon: "none",
              });
              return false;
          }

          // 检查是否选择了条田
          if (!this.$refs.sectionSelector.validate()) {
              uni.showToast({
                  title: "请选择至少一个条田",
                  icon: "none",
              });
              return false;
          }

          return true;
      },

      submitForm() {
          console.log(this.formData);
          // 使用uni-forms的验证方法
          this.$refs.form
              .validate()
              .then((result) => {
                  console.log("验证结果");
                  console.log(result);
                  console.log(this.validateForm());
                  if (this.validateForm()) {
                      this.submitFormData();
                  }
              })
              .catch((errors) => {
                  console.log("表单错误信息：", errors);
              });
      },
      async submitFormData() {
          try {
              // 获取选中的地块和条田
              this.updateSelectedLands();
              this.updateSelectedSections();

              let plotId = this.selectedLands.map((item) => item.id);
              let fieldId = this.selectedSections.map((item) => item.id);

              let plotName = this.selectedLands.map((item) => item.name);
              let fieldName = this.selectedSections.map((item) => item.name);
              console.log('提交表单1：');
              console.log(this.selectedLands, this.selectedSections);

              // 从imageUploader组件获取最新的图片列表
              const imageList = this.$refs.imageUploader.getImageList();

              // 构建提交的数据对象
              const submitData = {
                  id: this.isEdit ? this.editId : undefined,
                  startDate: this.formData.dateRange[0],
                  endDate: this.formData.dateRange[1],
                  plotId: plotId?.join(","), // 地块ID
                  fieldId: fieldId?.join(","), // 条田ID
                  plotName: plotName?.join(","), // 地块名称
                  fieldName: fieldName?.join(","), // 条田名称
                  area: parseFloat(this.formData.area),
                  sowingMethod: this.formData.sowingMethod,
                  machineryName: this.formData.machineryName,
                  machineryId: "", // 根据实际需求设置
                  cropType: this.formData.cropType,
                  cropName: this.formData.cropType, // 与cropType保持一致
                  seedName: this.formData.seedName,
                  seedId: this.formData.seedName, // 与seedName保持一致
                  personInCharge: this.formData.personInCharge,
                  personInId: this.formData.personInId, // 根据实际需求设置
                  images: imageList?.join(","), // 图片URL拼接
                  remark: this.formData.remark || "",
                  disasterLevel: this.formData.disasterLevel,
                  disasterType: this.formData.disasterType,
                  impactDescription: this.formData.impactDescription,
              };

              uni.showLoading({
                  title: "提交中...",
              });

              // 调用API创建或更新播种记录
              let res;
              if (this.isEdit) {
                  res = await weatherDisaster.updateDisasterWeather(submitData);
              } else {
                  res = await weatherDisaster.createDisasterWeather(submitData);
              }

              uni.hideLoading();

              if (res.code === 0) {
                  uni.showToast({
                      title: this.isEdit ? "修改成功" : "添加成功",
                      icon: "success",
                      duration: 2000,
                      success: () => {
                          setTimeout(() => {
                              // 返回上一页并刷新
                              uni.navigateBack({
                                  delta: 1,
                              });
                          }, 1500);
                      },
                  });
              } else {
                  uni.showToast({
                      title: res.msg || "操作失败",
                      icon: "none",
                      duration: 2000,
                  });
              }
          } catch (error) {
              uni.hideLoading();
              console.error("提交数据失败:", error);
              uni.showToast({
                  title: "提交失败，请重试",
                  icon: "none",
                  duration: 2000,
              });
          }
      },
  },
};
</script>

<style lang="scss">
.severity-options {
    display: flex;
    gap: 20rpx;
    
    .severity-item {
        flex: 1;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #666;
        position: relative;
        
        &.active {
            &:nth-child(1) {
                background-color: #E8F5E9;
                color: #4CAF50;
                border: 1px solid #4CAF50;
            }
            
            &:nth-child(2) {
                background-color: #FFF3E0;
                color: #FF9800;
                border: 1px solid #FF9800;
            }
            
            &:nth-child(3) {
                background-color: #FFEBEE;
                color: #F44336;
                border: 1px solid #F44336;
            }
        }
        
        .severity-indicator {
            width: 16rpx;
            height: 16rpx;
            border-radius: 50%;
            margin-right: 8rpx;
            
            &.mild {
                background-color: #4CAF50;
            }
            
            &.medium {
                background-color: #FF9800;
            }
            
            &.severe {
                background-color: #F44336;
            }
        }
    }
}

.unit-with-clear {
    display: flex;
    align-items: center;
    gap: 10rpx;
    
    .clear-icon {
        font-size: 24rpx;
        color: #999;
        cursor: pointer;
    }
}
</style>
